<?php
/**
 * Created by PhpStorm.
 * Author: 芸签cms www.yunqiancms.com
 * User: sun
 * Date: 2022/6/27
 * Time: 3:53 PM
 */
namespace app\backend\modules\sys\controllers;

use app\backend\controllers\BaseController;
use app\backend\modules\sys\services\RoleService;
use app\common\models\Role;
use app\backend\modules\sys\services\PermissionService;
use app\common\models\Permission;
use app\common\helpers\Cache;
use function Psy\debug;


class RoleController extends BaseController
{
    public function index(){
        return view("backend.sys.role.index");
    }
    public function getList(){
        $search = request()->search;
        $list = (new RoleService())->getList($search);
        return $this->successJson('',$list);
    }
    //获取某角色的所有权限
    public function permissions()
    {
        $id = request()->id;
        $permissions = [];
        $permissionModels = Permission::site()->select('permission')
            ->where('type', Permission::TYPE_ROLE)
            ->where('item_id',$id)
            ->get();
        if (!$permissionModels->isEmpty()) {
            foreach ($permissionModels as $v) {
                $permissions[] = $v['permission'];
            }
        }
        return $this->successJson('',$permissions);
    }
    public function changeStatus()
    {
        $id = request()->id;
        $model = Role::site()->select()
            ->where('id',$id)
            ->first();
        if (empty($model)) {
            return $this->errorJson('未找到数据');
        }
        $status=Role::STATUS_NORMAL;
        if($model->status==Role::STATUS_NORMAL){
            $status= Role::STATUS_BAN;
        }
        $model->status = $status;
        $model->save();
        return $this->successJson();
    }
    public function detail(){
        return view("backend.sys.role.detail");
    }
    public function getDetail(){
        $id = intval(request()->id);
        $permissions = PermissionService::getPermission();
        $permissions = PermissionService::getApiData($permissions);
        $rolePermission = [];
        $rolePermissions = [];
        if($id){
            $roleModel = Role::getRoleById($id);
            $rolePermission = $roleModel->toArray();
            foreach ($rolePermission['role_permission'] as $key) {
                $rolePermissions[] = $key['permission'];
            }
            if(empty($rolePermissions)) {
                $rolePermissions = [];
            }
        }
        $res = [
            'role'=>$rolePermission,
            'permissions'=>$permissions,
            'userPermissions'=>$rolePermissions
        ];
        return $this->successJson('',$res);
    }
    public function create(){
        $roleModel = new Role();
        $requestRole = request()->role;
        //dd($requestRole);
        if ($requestRole) {
            //将数据赋值到model
            $roleModel->setRawAttributes($requestRole);
            //其他字段赋值
            $roleModel->site_id = \YunCms::siteId();
            //字段检测
            $validator = $roleModel->validator($roleModel->getAttributes());
            //dd($validator->messages());
            if ($validator->fails()) {
                return  $this->errorJson("角色数据验证出错");

            }else{
                if ($roleModel->save()) {
                    $requestPermission = request()->permission;
                    //数据处理
                    if ($requestPermission) {
                        //dd(1);
                        $data = [];
                        foreach ($requestPermission as $key => $value) {
                            $data[$key] = array(
                                'type'      => Permission::TYPE_ROLE,
                                'item_id'   => $roleModel->id,
                                'permission' => $value
                            );
                            $validator = (new Permission)->validator($data);
                            if ($validator->fails()) {
                                return  $this->errorJson("角色数据验证出错");
                            }
                        }
                        \Log::debug('$requestPermission',$requestPermission);
                        $result = Permission::insert($data);
                        if (!$result) {
                            //删除刚刚添加的角色
                            Role::deleteRole($roleModel->id);
                            return  $this->errorJson("角色数据验证出错");
                        }
                    }
                    return $this->successJson('添加角色成功');
                } else {
                    $this->errorJson('角色数据写入出错，请重试！');
                }
            }
        }
    }
    public function update(){
        $requestRole = request()->role;
        $id = $requestRole['id'];
        $roleModel = Role::getRoleById($id);

        if ($requestRole) {
            $roleModel->setRawAttributes($requestRole);
            $validator = $roleModel->validator($roleModel->getAttributes());
            if ($validator->fails()) {
                $this->errorJson('权限数据验证失败');
            } else {
                if ($roleModel->save()) {
                    //return $this->message("更新角色成功");
                    Cache::flush();
                    $requestPermission = request()->permission;
                    if ($requestPermission) {
                        //dd(1);
                        $data = [];
                        foreach ($requestPermission as $key => $value) {
                            $data[$key] = array(
                                'type'      => Permission::TYPE_ROLE,
                                'item_id'   => $id,
                                'permission' => $value
                            );
                            $validator = (new Permission())->validator($data);
                            if ($validator->fails()) {
                                $this->errorJson('权限数据验证失败');
                            }
                        }
                        //删除原权限数据，更新数据储存
                        Permission::deleteRolePermission($id);
                        $result = Permission::insert($data);
                        if (!$result) {
                            //删除刚刚添加的角色
                            Role::deleteRole($id);
                            $this->errorJson('角色更新成功，权限数据写入出错，请重新编辑权限！');
                        } else {
                            return $this->successJson('编辑角色成功');
                        }
                    } else {
                        Permission::deleteRolePermission($id);
                    }
                    return $this->successJson('编辑角色成功');

                }
            }

        }
    }
    public function delete()
    {
        $id = request()->id;
        $requestRole = Role::getRoleById($id);
        if (!$requestRole) {
            return $this->errorJson('未找到数据或已删除');
        }
        $resultRole = Role::deleteRole($id);
        if ($resultRole) {
            $resultPermission = Permission::deleteRolePermission($id);
            return $this->successJson('删除角色成功。');
        } else {
            return $this->errorJson('数据写入出错，请重试！');
        }
    }
    public function query(){
        $kwd = trim(request()->kwd);
        $list = Role::site()->select(['id','name']);
        if($kwd){
            $list = $list->where('name','like','%'.$kwd.'%');
        }
        $list = $list
            ->orderBy('id', 'desc')
            ->take(1000)
            ->get();
        return $this->successJson('',$list);
    }
}